"""
mumu模拟器管理类。控制开关等一系列操作
"""
import json
import subprocess
import time

class ISimulatorManager:

    def __init__(self):
        self._checkStartTimeoutTime = 40 # 40s 启动不了就有问题
        self._startupcb = []

    def CheckStartupResult(self):
        #DebugPrint("Check startup result")
        if self._startupcb:
            dellist = []
            for name, cbfunc, begintime in self._startupcb:
                if self.CheckStartupFinished(name):
                    cbfunc()
                    dellist.append(name)
                else:
                    # 检查启动时间是否大于40秒，大于40秒说明有点问题，要重新启动一次
                    curtime = int(time.time())
                    difftime = curtime - begintime
                    if difftime >= self._checkStartTimeoutTime:
                        cbfunc(success = False)
                        dellist.append(name)
            for name in dellist:
                for tinfo in self._startupcb:
                    if tinfo[0] == name:
                        self._startupcb.remove(tinfo)
                        break

    def frame(self):
        self.CheckStartupResult()
        self.onFrame()
    
    def onFrame(self):
        pass

    def executeCommand(self, op, cmds):
        if str == type(cmds):
            cmds = [self._Executor, op] + cmds.split(" ")
        elif type(cmds) in (tuple, list):
            cmds = [self._Executor, op] + cmds
        else:
            raise Exception(f"Unknow args: {type(cmds)}, {cmds}")
        result = subprocess.run(cmds, stdout=subprocess.PIPE)
        # 打印输出结果
        return result.stdout.decode("utf8")
    
    def startDevice(self, devicename):
        pass

class MumuManager(ISimulatorManager):

    _cmdpath = "D:\\Program Files\\Netease\\MuMu Player 12\\shell\\MuMuManager.exe"
    
    def loadInfo(self):
        data = self.info("-v all")
        self._allmachines = json.loads(data)
        if "index" in self._allmachines:
            return {self._allmachines["index"]: self._allmachines}
        return self._allmachines
    
    def GetIndexByName(self, name: str):
        for v in self.loadInfo().values():
            if name == v["name"]:
                return v["index"]
        return -1
    
    def info(self, args):
        result = self.executeCommand("info", args)
        return result

    def control(self, args):
        result = self.executeCommand("control", args)
        return result
    
    def adb(self, args):
        result = self.executeCommand("adb", args)
        return result

    def startDevice(self, name, cbfunc):
        index = self.GetIndexByName(name)
        if -1 == index:
            DebugPrint(f"device {name} not found.")
            return False
        self.control(f"-v {index} restart")
        self._startupcb.append((name, cbfunc, int(time.time())))

    def stopDevice(self, name):
        index = self.GetIndexByName(name)
        if -1 == index:
            DebugPrint(f"device {name} not found.")
            return False
        self.control(f"-v {index} shutdown")

    def restartDevice(self, name):
        index = self.GetIndexByName(name)
        if -1 == index:
            DebugPrint(f"device {name} not found.")
            return False
        self.control(f"-v {index} restart")
        